package gov.pbc.nn.kjgl.software.dao;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.dao.AbstractJdbcDao;
import gov.pbc.nn.core.utils.EntityRowMapperUtils;
import gov.pbc.nn.core.utils.SecurityUtils;
import gov.pbc.nn.kjgl.entity.Project;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.bstek.bdf2.core.CoreJdbcDao;
import com.bstek.bdf2.core.business.IDept;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.orm.ParseResult;
import com.bstek.bdf2.core.service.IDeptService;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

@Repository
public class ProjectMangeJdbcDao extends  AbstractJdbcDao {	
	
	public void getAllPage(Page<Project> page, Criteria criteria) {
		Dept loginDept = (Dept) ContextHolder.getLoginUser().getDepts().get(0);
		Dept loginZZDept = (Dept) SecurityUtils.getZZByDept(loginDept);
		IDeptService ds = ContextHolder.getBean(IDeptService.BEAN_ID);
		List<IDept> children = ds.loadDeptsByParentId(loginZZDept.getId(), loginZZDept.getCompanyId());
		List<String> depts=new ArrayList<String>() ;
		for (IDept dept : children) {
			depts.add(dept.getId());
		}
		
		StringBuilder sqlsb=new StringBuilder("select * from t_project P where P.INVALID_=0 and P.STATE_=:number ");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("number", 10);	
		if (Dept.NANNING.equals(loginZZDept.getId())==false) {
			sqlsb.append( " and P.PROJECT_DEPT_ in (:ZZDeptId) ");
			params.put("ZZDeptId", depts);
		}

		ParseResult pr = this.parseCriteria(criteria, true, "P");	
		if (pr != null) {
			StringBuffer sbSql = pr.getAssemblySql();
			sqlsb.append( " and " + sbSql.toString()) ;
			params.putAll(pr.getValueMap());
		}
		
		sqlsb.append(  " order by CREATE_DATE_ desc");

		this.pagingQuery(page, sqlsb.toString(), new RowMapper<Project>() {

			@Override
			public Project mapRow(ResultSet rs, int rowNum) throws SQLException {
				return EntityRowMapperUtils.get(Project.class, rs, rowNum);
			}
		}, params);

	}
}
